import 'package:flutter/foundation.dart';
import 'package:flutter_common/util/logger.dart';
import 'package:intl/intl.dart';

import 'logger.dart';

class StringUtils {

  StringUtils._();

  static bool isBlank(String? str) {
    if (str == null || str.isEmpty) {
      return true;
    }
    return false;
  }

  static bool equals(String? string1, String? string2) {
    if (string1 == null && string2 == null) return true;
    if (string1 == null || string2 == null) return false;
    return string1.compareTo(string2) == 0;
  }

  ///将字符串的部分内容使用[placeHolder]代替
  static String replacePart(
      String? str, String placeHolder, int startPosition, int replaceLength) {
    if (str.isNullOrEmpty) return "";
    if (placeHolder.isEmpty) return str!;
    if (str!.length < startPosition + replaceLength) return str;

    StringBuffer placeHolderStr = StringBuffer();
    for (int i = 0; i < replaceLength; i++) {
      placeHolderStr.write(placeHolder);
    }
    return str.replaceRange(startPosition, startPosition + replaceLength,
        placeHolderStr.toString());
  }

  ///将身份证号脱敏
  static String hideIDCardNo(String? str) {
    if (str.isNullOrEmpty) return "";
    if(str!.length < 15) return str;
    return replacePart(str,'*',6,str.length - 10);
  }

  ///将手机号码脱敏
  static String hidePhone(String? str) {
    if (str.isNullOrEmpty) return "";
    if (str!.length < 10) return str;
    return replacePart(str, '*', 3, str.length - 7);
  }

  static String objectToString(dynamic obj) {
    if (obj == null) {
      return "";
    }
    return obj.toString();
  }

  ///将字符串数组使用[separator]拼接为一串字符串
  static String mergeList(List<String>? list, [String separator = ',']) {
    if(list == null || list.isEmpty) return "";
    StringBuffer buffer = StringBuffer();
    buffer.writeAll(list, separator);
    return buffer.toString();
  }

  ///[intTime] int格式的时间值，对应安卓的则是 long
  static String formatTime(String pattern,{int? intTime, DateTime? dateTime}) {
    if(dateTime == null && intTime == null) return "";
    if(dateTime != null) {
      return DateFormat(pattern).format(dateTime);
    }
    if(intTime! <= 0) return "";
    return DateFormat(pattern).format(DateTime.fromMillisecondsSinceEpoch(intTime));
  }

  //将指定格式的时间，转为时间戳；如果本身为时间戳，则直接转long并返回；时间为空，则直接返回0
  static int parseFormatTime(String pattern, String? time) {
    if (time.isNullOrEmpty) {
      return 0;
    }
    DateFormat format = DateFormat(pattern);
    try {
      return format.parse(time!).millisecondsSinceEpoch;
    } catch (e) {
      return time.toInt();
    }
  }

  ///只能处理 '20231124144631' 和 '20231124144631139' 这2种格式的时间字符串
  static DateTime? parseTime(String? time) {
    if (time.isNullOrEmpty) {
      return null;
    }
    int t1 = time!.substring(14).toInt();
    String t = '${time.substring(0,8)}T${time.substring(8, 14)}';
    return DateTime.parse(t).add(Duration(milliseconds: t1));
  }

  ///将指定的秒数转换成00:00:00格式时间，例如：65转换后为00:01:05
  static String getFormatDuration(int duration) {
    int time = duration % 3600;
    int hour = duration ~/ 3600;
    int minute = time ~/ 60;
    int second = time % 60;
    return "${hour.toString().padLeft(2,"0")}:${minute.toString().padLeft(2,"0")}:${second.toString().padLeft(2,"0")}";
  }

  /// 校验手机号格式
  static bool validatePhoneNumber(String input) {
    // 定义一个正则表达式，匹配中国大陆手机号
    RegExp mobilePattern = RegExp(r'^1[3456789]\d{9}$');
    return mobilePattern.hasMatch(input);
  }

  /// 校验密码是否符合格式。6-20字符，至少包含英文字母、数字。特殊符号两种
  static bool validatePassword(String input,[int min = 6, int max = 20]) {
    String s = r"^(?=.*?[A-Za-z])(?=.*?[0-9@\$!%*#?&])[A-Za-z0-9@\$!%*#?&]{" + "$min,$max" + r"}$";
    RegExp mobilePattern = RegExp(s);
    return mobilePattern.hasMatch(input);
  }

  /// 校验邮箱的正则表达式
  static bool validEmail(String input) {
    final RegExp regex = RegExp(r"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
    return regex.hasMatch(input);
  }

  /// 校验用户名
  static bool validateAccount(String input, [int min = 1, int max = 20]) {
    RegExp regex = RegExp(r'^(?![0-9]+$)[a-zA-Z0-9]{1,20}$');
    return regex.hasMatch(input);
  }

  static int parseInt(dynamic obj, [int defaultValue = 0]) {
    try {
      if (obj == null) return 0;
      if (obj is num) return obj.toInt();
      if (obj is String) return obj.toInt();
      return obj.toString().toInt();
    } catch(e) {
      logger.error(e);
      return defaultValue;
    }
  }
}

extension StringExtension on String? {

  bool get isNullOrEmpty => this == null || this!.isEmpty;

  bool get isNotEmpty => !isNullOrEmpty;

  bool equals(String? string2) => StringUtils.equals(this, string2);

  bool noEquals(String? string2) => !equals(string2);

  double toDouble({double defaultValue = 0}) => toNullableDouble(defaultValue: defaultValue)!;

  /// 字符串转int 如果没有，则返回[defaultValue]
  int toInt({int defaultValue = 0}) => toNullableInt(defaultValue: defaultValue)!;

  /// 判断是否为 null 或者空字符组成的字符串
  bool get isNullOrBlank => isNullOrEmpty || this!.trim().isEmpty;

  /// 不是空字符组成的字符串
  bool get isNotBlank => !isNullOrBlank;


  /// 字符串转int 如果没有，则返回[defaultValue]
  int? toNullableInt({int? defaultValue, String? key}) {
    if (isNullOrBlank) {
      return defaultValue;
    }
    final String self = this!;
    int p = self.indexOf('.');
    try {
      if (p == -1) {
        return int.parse(self);
      } else {
        return int.parse(self.substring(0, p));
      }
    } catch (e) {
      if (kDebugMode) {
        print("key:$key, value:$this,parse int err.$e");
      }
      return defaultValue;
    }
  }

  double? toNullableDouble({double? defaultValue}) {
    if (isNullOrBlank) {
      return defaultValue;
    }
    final String self = this!;
    try {
      return double.parse(self);
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
      return defaultValue;
    }
  }

  ///获取字符串的后缀名
  String suffix(Pattern pattern) {
    if(this == null) return '';
    return this!.split(pattern).last;
  }

  ///扩展名
  String get ext {
    if(this == null) return '';
    List<String> p = this!.split('.');
    if(p.length > 1) return p.last;
    return '';
  }

  ///调整字符串换行规则，以尽可能的展示全部（主要体现在文字太长需要省略号的情况下）
  String get re {
    if(this == null) return '';
    return this!.split('').join('\u200B');
  }
}